package com.chen.demo.config;

import java.io.IOException;

import javax.sql.DataSource;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

//处理事务

@Configuration
public class SessionFactoryConfiguration {

	@Value("${mybatis_config_file}")
	private String mybatisConfigFilePath;
	@Value("${mapper_path}")
	private String mapperPath;
	@Value("${domain_package}")
	private String domainPackage;

	@Autowired
	@Qualifier("dataSource")
	private DataSource dataSource;

	@Bean(name = "sqlSessionFactory")
	public SqlSessionFactoryBean creaBean() throws IOException {

		PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		String path = PathMatchingResourcePatternResolver.CLASSPATH_URL_PREFIX + mapperPath;

		SqlSessionFactoryBean sql = new SqlSessionFactoryBean();
		sql.setConfigLocation(new ClassPathResource(mybatisConfigFilePath));
		sql.setMapperLocations(resolver.getResources(path));
		sql.setDataSource(dataSource);
		sql.setTypeAliasesPackage(domainPackage);

		return sql;
	}
}
